/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import preparedstatement.DebugLevel;
import preparedstatement.StatementFactory;

/**
 *
 * @author Alfredo
 */
public class devolucion extends javax.swing.JFrame {
DecimalFormat nf;
    public static Connection cn;
    public static PreparedStatement ps;
    public static ResultSet rs;
    String can = "";
    int canti, moti, codigo, venta, sucursal, devueltos = 0;

    /**
     * Creates new form devolucion
     */
    public devolucion(int codi, float can, int ven, int sucu, String nombre) {
        initComponents();
        jRadioButton1.setSelected(true);
        nf = new DecimalFormat("#,###,###,##0.00");
        jTextField1.setDocument(new devolucion.LimitadorCaracteres());
        codigo = codi;
        canti = (int) can;
        venta = ven;
        sucursal = sucu;
        cargarDevueltos();
        pordevolver.setText(String.valueOf(canti - devueltos));
        devueltosLabel.setText(String.valueOf(devueltos));
        jLabel6.setText("" + nombre);
    }

    void cargarDevueltos() {
        try {
            ps = local_connection.cn.prepareStatement("select cantidad from devoluciones where idproducto = ? and idventa = ?");
            ps.setInt(1, codigo);
            ps.setInt(2, venta);
            rs = ps.executeQuery();
            if (rs.next()) {
                devueltos = rs.getInt(1);
            }
           // System.out.println(ps);
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
    }

    class LimitadorCaracteres extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        @Override
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!Character.isDigit(arg1.charAt(i))) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        cancelar = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        pordevolver = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        observaciones = new javax.swing.JTextArea();
        jLabel8 = new javax.swing.JLabel();
        devueltosLabel = new javax.swing.JLabel();

        jButton2.setText("jButton2");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Devoluciones");

        jLabel2.setText("Cantidad a devolver:");

        jTextField1.setText("jTextField1");

        jLabel3.setText("Motivo:");

        buttonGroup1.add(jRadioButton1);
        jRadioButton1.setText("Mal funcionamiento");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setText("Cambio");

        cancelar.setText("Cancelar");
        cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });

        jButton3.setText("Aceptar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel4.setText("Cantidad Maxima:");

        pordevolver.setText("jLabel5");

        jLabel6.setText("jLabel6");

        jLabel7.setText("Observaciones:");

        observaciones.setColumns(20);
        observaciones.setRows(5);
        jScrollPane1.setViewportView(observaciones);

        jLabel8.setText("Cantidad Devuelta:");

        devueltosLabel.setText("jLabel9");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(107, 107, 107)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jRadioButton1)
                                            .addComponent(jRadioButton2, javax.swing.GroupLayout.Alignment.LEADING)))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(34, 34, 34)
                                        .addComponent(jLabel3))))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel7)
                                    .addComponent(pordevolver, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(84, 84, 84)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel8)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(25, 25, 25)
                                        .addComponent(devueltosLabel)))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cancelar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addGap(20, 20, 20))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(69, 69, 69)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jRadioButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jRadioButton2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pordevolver)
                    .addComponent(devueltosLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancelar)
                    .addComponent(jButton3))
                .addGap(17, 17, 17))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
        this.dispose();// TODO add your handling code here:
    }//GEN-LAST:event_cancelarActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        int cantidadIngresada = 0;
        float dinero = 0.0f;
        if (jTextField1.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Ingresa la cantidad a devolver");
        } else {
            cantidadIngresada = Integer.parseInt(jTextField1.getText());
        }
        if (cantidadIngresada > 0 && cantidadIngresada <= (canti - devueltos)) {
            try {
                ps = local_connection.cn.prepareStatement("select preciovendido from detalleventa where folio = ? and id_producto = ?");
                ps.setInt(1, venta);
                ps.setInt(2, codigo);
                rs = ps.executeQuery();
                rs.next();
                dinero = cantidadIngresada * rs.getFloat(1);
                ps = local_connection.cn.prepareStatement("select (select preciovendido from detalleventa where id_producto =-1 and modo like 'Porcentaje' and folio = ? )/sum(if(id_producto!=-1,preciovendido,0)) from detalleventa where folio=?");
                ps.setInt(1, venta);
                ps.setInt(2, venta);
                rs = ps.executeQuery();
                rs.next();
                if (rs.getObject(1) != null) {
                    dinero += (dinero * rs.getFloat(1));
                }
                if (jRadioButton1.isSelected()) {
                    moti = 1;
                }
                if (jRadioButton2.isSelected()) {
                    moti = 2;
                    ps = StatementFactory.getStatement(local_connection.cn, "Update stock set cantidad=cantidad+" + cantidadIngresada + " where id_producto=" + codigo + " and sucursal = " + VentanaPrincipal.sucursal, DebugLevel.ON);
                    ps.execute();
                    VentanaPrincipal.guardarCache(ps, "stock", true);
                }

                ps = StatementFactory.getStatement(local_connection.cn, "insert into devoluciones(idproducto,cantidad,motivo,idventa,fecha,sucursal,observaciones,dinero,caja) values(?,?,?,?,CURRENT_TIMESTAMP,?,?,?,?)", DebugLevel.ON);
                ps.setInt(1, codigo);
                ps.setInt(2, cantidadIngresada);
                ps.setInt(3, moti);
                ps.setInt(4, venta);
                ps.setInt(5, sucursal);
                ps.setString(6, observaciones.getText());
                ps.setFloat(7, dinero);
                ps.setInt(8,VentanaPrincipal.caja);
                ps.execute();
                VentanaPrincipal.guardarCache(ps, "devoluciones", true);
                JOptionPane.showMessageDialog(null, "Devolver la cantidad de\n$" + nf.format(dinero));
                /* ps=StatementFactory.getStatement(local_connection.cn,"Update detalleventa set cantidad=cantidad-"+a+" where folio = " + venta+" and id_producto ="+codigo,DebugLevel.ON);
                 ps.execute();
                 VentanaPrincipal.guardarCache(ps, "detalleventa", true);*/

            } // TODO add your handling code here:
            catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(null, "Error");
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jRadioButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cancelar;
    private javax.swing.JLabel devueltosLabel;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextArea observaciones;
    private javax.swing.JLabel pordevolver;
    // End of variables declaration//GEN-END:variables
}
